package com.apes.framework.condition;

import com.alibaba.fastjson.JSON;
import com.apes.framework.plugin.fileserver.File;
import com.apes.framework.util.MapUtil;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = "*", maxAge = 3600)  // 允许所有域名访问
@Controller
public class XlsFileController {

    /**
     * 上传
     *
     * @param file
     * @return id
     */
    @PostMapping(value = "/fileserver/import", produces = {"text/html;charset=utf-8"})
    @ResponseBody
    public ResponseEntity<String> handleFileUpload(@RequestParam("files") MultipartFile file) throws Exception {
        List result = new ArrayList();
        String type=file.getContentType();
        String filename=null;
        String ext=null;
        switch (type){
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
                ext="xlsx";
                break;
            }
            case "application/vnd.ms-excel": {
                ext="xls";
                break;
            }
            case "text/plain": {
                ext="txt";
                break;
            }
            case "text/xml": {
                ext="xml";
                break;
            }
            case "application/octet-stream": {
                ext="rar";
                break;
            }
        }

        filename=LocalVariable.getTempDir()+file.getOriginalFilename();
        FileUtil.createDir(filename);
        FileUtil.byteToFile(filename,file.getBytes());
        result.add(MapUtil.mapper(
                "type", ext,
                "size", file.getSize(),
                "name", file.getOriginalFilename()));
        return ResponseEntity.status(HttpStatus.OK).body(JSON.toJSONString(result));  //需要测试该文件上传服务器的逻辑，要求不上传，存本地
    }

}
